package com.shangcheng.server.service;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.convert.Convert;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.shangcheng.dubbo.api.SmsHomeBrandApi;
import com.shangcheng.model.domain.SmsHomeBrand;
import com.shangcheng.model.vo.PageResult;
import com.shangcheng.server.exception.BusinessException;
import org.apache.commons.collections.ListUtils;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import java.util.List;

/**
 * @author shiqiang
 * @version 1.0
 * @date 2022/5/12 15:07
 */
@Service
public class SmsHomeBrandService {
    @DubboReference
    private SmsHomeBrandApi smsHomeBrandApi;

    /**
     * 根据条件查询推荐品牌
     * @param pageNum 当前页
     * @param pageSize 每页条目数
     * @param brandName 品牌名称
     * @param recommendStatus 推荐状态
     * @return
     */
    public PageResult brandList(Integer pageNum,Integer pageSize,String brandName,Integer recommendStatus) {
        //1.查询品牌推荐表获取推荐品牌对象
        IPage<SmsHomeBrand> page=smsHomeBrandApi.findByCondition(pageNum,pageSize,brandName,recommendStatus);
        return new PageResult(Convert.toInt(page.getCurrent()),Convert.toInt(page.getSize()),Convert.toInt(page.getTotal()),page.getRecords());
    }

    /**
     * 修改推荐品牌排序
     * @param id
     * @param sort
     */
    public void updateSort(Integer id, Integer sort) {
        smsHomeBrandApi.updateSort(id,sort);
    }

    /**
     * 批量删除推荐品牌列表
     * @param ids
     */
    public void delete(Integer[] ids) {
        smsHomeBrandApi.deleteByIds(ids);
    }

    /**
     * 批量修改推荐状态
     * @param ids ids
     * @param recommendStatus 推荐状态
     */
    public void updateRecommendStatus(Integer[] ids, Integer recommendStatus) {
        smsHomeBrandApi.updateRecommendStatus(ids,recommendStatus);
    }

    /**
     * 批量添加推荐品牌
     * @param homeBrandList 推荐品牌集合
     */
    public void create(List<SmsHomeBrand> homeBrandList) {
        //根据品牌名称查询数据库
        List<SmsHomeBrand> homeBrands= smsHomeBrandApi.findByBrandName(homeBrandList);
        if (!ObjectUtils.isEmpty(homeBrands)){
            //如果存在,抛出异常
            List<String> brandNames = CollUtil.getFieldValues(homeBrands, "brandName", String.class);
            throw new BusinessException(brandNames.toString()+"已存在");
        }
        smsHomeBrandApi.create(homeBrandList);
    }
}
